package com.zhangtai.modules.controller.aouthLogin;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.zhangtai.exception.RException;
import com.zhangtai.modules.constVo.SystemConst;
import com.zhangtai.modules.controller.admin.JobController;
import com.zhangtai.modules.dao.*;
//import com.zhangtai.modules.dao.ssqlDao.JobDaoMssql;
import com.zhangtai.modules.dto.EmployeeCachDto;
import com.zhangtai.modules.entity.employee.EmployeeInfoEntity;
import com.zhangtai.modules.entity.employee.PromotionEntity;
import com.zhangtai.modules.entity.regular.RegularBpmEntity;
import com.zhangtai.modules.entity.system.ContractSubGroupEntity;
import com.zhangtai.modules.entity.system.ContrarctUserEntity;
import com.zhangtai.modules.entity.system.UserEntity;
import com.zhangtai.modules.entity.system.UserGroupEntity;
import com.zhangtai.modules.service.login.JwtEncodeAndEncode;
import com.zhangtai.modules.service.login.UserEntityOauth;
import com.zhangtai.modules.vo.PasswordVo;
import com.zhangtai.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @Author: ming
 * @Date: 2020/6/3 0003 下午 4:02
 */

@RestController
@Slf4j
@Api(tags="登录接口")
public class LoginController {

    private static final String CookieName="Authorization";

    @Autowired
    private UserDao userDao;
    @Autowired
    private JwtEncodeAndEncode jwtEncodeAndEncode;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrgGroupDao orgGroupDao;
    @Autowired
    private QwUserDao qwUserDao;
    @Autowired
    private UserGroupDao userGroupDao;
    @Autowired
    private JobController jobController;
//    @Autowired
//    private JobDaoMssql jobDaoMssql;

    @Autowired
    private ContractSubGroupDao contractSubGroupDao;


    @Autowired
    PasswordEncoder passwordEncoder;
    @Autowired
    private EmployeeInfoDao employeeInfoDao;
    @Autowired
    private ContrarctUserDao contrarctUserDao;

//    @Autowired
//    private




    @GetMapping("/getUserInfo")
    @ApiOperation(value="获取用户信息")
    public R<JSONObject> getUserInfo(HttpServletRequest request) throws Exception{


        String cookieValue = CookieUtils.getCookieValue(request, CookieName);
//        String cookieValue = request.getHeader("Authorization").replace("Bearer ","");

        if (StringUtils.isEmpty(cookieValue)){
            return R.error("cookieValue为空");
        }
        String decode=null;
        try {
//            log.info("开始解析");
            decode = jwtEncodeAndEncode.decode(cookieValue);
//            log.info("decode:{}",decode);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RException("token解析失败");
        }
        JSONObject user = JSON.parseObject(decode, JSONObject.class);
        Long id = user.getLong("id");
        String code = user.getString("usercode");
//从redis中取出menu
//        HashSet<String> hashSet = (HashSet<String>) redisTemplate.boundValueOps("userMenu" + id).get();
//        从redis中获取管理员的员工信息
        EmployeeCachDto employeeCachDto = (EmployeeCachDto) redisTemplate.boundValueOps("employeeInfo" + code).get();

        UserEntity userEntity = userDao.selectById(id);
        List<String> menuByUserId = userDao.findMenuByUserId(userEntity.getUserId());
        HashSet<String> hashSet = new HashSet<>();
        for (String s : menuByUserId) {
            if (!StringUtils.isEmpty(s)){
                hashSet.add(s);
            }
        }
//        如果员工信息为空，则去查询用户表
        if (ObjectUtils.isEmpty(employeeCachDto)){
              userEntity = userDao.selectById(id);
            employeeCachDto=new EmployeeCachDto();
            employeeCachDto.setJobId(userEntity.getJobId());
            employeeCachDto.setUnitId(userEntity.getDepId());
            employeeCachDto.setOrgId(userEntity.getOrgId());
        }



        user.put("menu",hashSet);
        Long orgId = employeeCachDto.getOrgId();
        Long depId = employeeCachDto.getUnitId();
        Long jobId = employeeCachDto.getJobId();
//        String org = jobController.getOrgNameById(orgId);
//        String unit = jobController.getOrgNameById(depId);
//        String jobName = jobController.getJobName(jobId);
//        user.put("jobname",jobName);
//        user.put("orgname",org);
//        user.put("department",unit);
        user.put("orgId",orgId);
        user.put("depId",depId);
        user.put("jobId",jobId);



//        log.info("获取管理员登录信息user:{}",user);
        return R.ok(user);


    }


    @PostMapping("/loginByUserAndPwd")
    @ApiOperation(value="账号密码登录接口")
    public R login(@RequestBody @Valid PasswordVo passwordVo) throws Exception {
        String username = passwordVo.getUsername();
        String pwd = passwordVo.getPassword(); //AES解密
        String password = AESUtil.aesDecrypt(pwd);
//        String password = pwd;
        UserEntity userEntity = userDao.selectOne(new QueryWrapper<UserEntity>().eq("username", username).or().eq("usercode",username)
        .or().eq("mobile",username).eq("is_delete",0));
        if (ObjectUtils.isEmpty(userEntity)){
            return R.error("查不到该用户");
        }
        Integer i=0;
        if(i.equals(userEntity.getStatus())){
            return R.error("您的账户已禁用,请联系管理员!");
        }
        if(!passwordEncoder.matches(password,userEntity.getPassword())){
            return R.error("登录密码输入错误！");
        }
        String usercode = userEntity.getUsercode();
//        拦截掉离职的
        EmployeeInfoEntity employeeInfoEntity = employeeInfoDao.selectOne(new QueryWrapper<EmployeeInfoEntity>().eq("code", usercode).eq("is_delete", 0));

        if (!ObjectUtils.isEmpty(employeeInfoEntity)){
            String employeestatus = employeeInfoEntity.getEmployeestatus();
            if (!StringUtils.isEmpty(employeestatus)){
                if (!"2".equals(employeestatus)&&!"9".equals(employeestatus)){
                    return R.error("您已离职，无法登录");
                }
            }
        }

//
//        List<EmployeeInfoEntity> empByCodeAll = jobDaoMssql.findEmpByCodeAll(usercode);
//
//        if (!CollectionUtils.isEmpty(empByCodeAll)){
//            for (EmployeeInfoEntity entity : empByCodeAll) {
//                String employeestatus1 = entity.getEmployeestatus();
//                if (!StringUtils.isEmpty(employeestatus1)){
//                    if (!"2".equals(employeestatus1)&&!"9".equals(employeestatus1)){
//                        return R.error("您已离职，无法登录");
//                    }
//                }
//            }
//
//        }




        List<String> perms = userDao.findPermsByUserId(userEntity.getUserId());
        HashSet<String> hashSet = new HashSet<>();
        if (!CollectionUtils.isEmpty(perms)){
            for (String perm : perms) {

                if (!StringUtils.isEmpty(perm)){
                    hashSet.add(perm);
                }

            }

        }
//        List<RoleEntity> role = userDao.listRolesByUserId(userEntity.getUserId());
//
        UserEntityOauth sysUserOauth = BeanUtilsMabach.doToDto(userEntity, UserEntityOauth.class);
        sysUserOauth.setAuthorities(hashSet);
//        sysUserOauth.setRole(role);


//加密成token冰存到cookie里
        String token = jwtEncodeAndEncode.encodeUser(sysUserOauth);
        log.info("管理员{}登陆成功，信息：{}",sysUserOauth.getName(),sysUserOauth);
//        log.info("管理员{}登陆成功,token{}",sysUserOauth.getName(),token);



        return R.ok();
    }


    public R checkContractPermission(HttpServletRequest request) throws Exception {
        JSONObject  user = getUserInfo(request).getData();


        if(com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isEmpty(user)){
            return R.error(SystemConst.loginInfoErro,"请先登录再查询！");
        }
        String userId = user.getString("id");


        List<Long> contractGoupIds= (List<Long>) redisTemplate.boundValueOps("contractPermission"+userId).get();

        if(org.springframework.util.CollectionUtils.isEmpty(contractGoupIds)){
            List<ContrarctUserEntity> contrarctUserEntityList= contrarctUserDao.selectList(new QueryWrapper<ContrarctUserEntity>()
                    .eq("user_id",userId));
            if(!org.springframework.util.CollectionUtils.isEmpty(contrarctUserEntityList)){
                contractGoupIds=new ArrayList<>();
                for (ContrarctUserEntity contrarctUserEntity:contrarctUserEntityList){
                    contractGoupIds.add(contrarctUserEntity.getContractMainId());
                }
                HashSet set = new HashSet(contractGoupIds);
                //把List集合所有元素清空
                contractGoupIds.clear();
                //把HashSet对象添加至List集合
                contractGoupIds.addAll(set);
            }
        }

        //获取缓存中的主体组id
        if(com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isEmpty(contractGoupIds)) {
            return R.error(SystemConst.loginInfoErro,"登录用户没有权限！");

        }else{
          //  contractGoupIds = (List<Long>) redisTemplate.boundValueOps("contractPermission"+userId).get();
            //根据主体组id查询主体ids
            List<ContractSubGroupEntity> contractMainIds=null;
            if(!CollectionUtils.isEmpty(contractGoupIds)) {
                contractMainIds = contractSubGroupDao.getContractMainIds(contractGoupIds);
            }
            return R.ok(contractMainIds);

        }


    }


    @GetMapping("/exit")
    @ApiOperation(value="登出")
    public R logOut(HttpServletRequest request, HttpServletResponse response){
        String cookieValue = CookieUtils.getCookieValue(request, CookieName);
        if (StringUtils.isEmpty(cookieValue)){
            return R.error("cookieValue为空");
        }
        String decode=null;
        try {
//            log.info("开始解析");
            decode = jwtEncodeAndEncode.decode(cookieValue);
//            log.info("decode:{}",decode);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RException("token解析失败");
        }
        JSONObject user = JSON.parseObject(decode, JSONObject.class);
        String uuid = user.getString("uuid");

        redisTemplate.delete(uuid);
        CookieUtils.deleteCookie(request,response,CookieName);
        return R.ok();
    }





    /**
     * 角色公司校验
     * @param request
     * @param beforeOrgId
     * @param isCompare
     * @return
     * @throws Exception
     */
    @GetMapping("/checkOrgPermission")
    @ApiOperation(value="部门校验接口")
    public R checkOrgPermission(HttpServletRequest request,Long beforeOrgId,boolean isCompare) throws  Exception{
        JSONObject  user = getUserInfo(request).getData();


        if(ObjectUtils.isEmpty(user)){
            return R.error(SystemConst.loginInfoErro,"请先登录再查询！");
        }
        String userId = user.getString("id");


        List<Long> orgIds=null;
        //获取缓存中的公司信息
        if(ObjectUtils.isEmpty(redisTemplate.boundValueOps("orgPermission"+userId).get())) {
            Long u = Long.parseLong(userId);
            orgIds = updateUsrOrgPermission(u);

        }else{
           orgIds = (List<Long>) redisTemplate.boundValueOps("orgPermission"+userId).get();
        }
        boolean isPermission = false;
        //是否校验公司信息（接口功能权限校验时用）
        if(isCompare){
            for(Long id:orgIds){
                if(id.equals(beforeOrgId)){
                    isPermission = true;
                    break;
                }
            }
            if(!isPermission){
               return R.error(SystemConst.orgPermissionErro,"公司权限不够，您无权进行操作");
            }else{
                return R.ok(user);
            }
        }
        //不校验公司信息返回角色下所有公司Id(查询时用)
        else{
            return R.ok(orgIds);
        }

    }

    /**
     * 更新用户公司组信息
     * @param userId
     * @return
     */
    public List<Long> updateUsrOrgPermission(Long userId) {
        List<Long> orgIds = new ArrayList<Long>();//获取用户对应组织
        List<UserGroupEntity> groupList = userGroupDao.selectList(new QueryWrapper<UserGroupEntity>().eq("user_id", userId).eq("is_delete",0));
        List<Long> groupIds = new ArrayList<>();
        for(UserGroupEntity group:groupList){
            groupIds.add(group.getGroupId());
        }
        //取组织对应公司Id
        List<Long>o = orgGroupDao.getOrgIdsByGroup(groupIds);
        for(Long orgId:o){
            if(!ObjectUtils.isEmpty(jobController.orgAllChildrenMap.get(orgId))){
                orgIds.addAll(jobController.orgAllChildrenMap.get(orgId));
            }

        }

        if(orgIds.size()>1||(orgIds.size()==1&&orgIds.get(0)!=null)){
            redisTemplate.boundValueOps("orgPermission"+userId).set(orgIds,60, TimeUnit.MINUTES);
        }else{
            redisTemplate.boundValueOps("orgPermission"+userId).set(null);
        }
        return orgIds;
    }


    /**
     * 新员工转正导入
     * @return
     */
    @GetMapping("/test2")
    public R test2() {
//        File file = new File("/Users/lishenhong/Desktop/usercode.txt");
//        BufferedReader reader = null;
//        String tempString = null;
//        int line =1;

        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("ZT010372");
//        arrayList.add("ZT026853");









//
//        try {
//
//            reader = new BufferedReader(new FileReader(file));
//            while ((tempString = reader.readLine()) != null) {
//
//                arrayList.add(tempString);
//                line ++ ;
//            }
//            reader.close();
//        } catch (Exception e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//
//        }finally{
//            if(reader != null){
//                try {
//                    reader.close();
//                } catch (IOException e) {
//                    // TODO Auto-generated catch block
//                    e.printStackTrace();
//                }
//            }
//        }
        System.out.println(arrayList.size());
        int i=0;
        for (String s : arrayList) {
            EmployeeInfoEntity empByCode = employeeInfoDao.selectOne(new QueryWrapper<EmployeeInfoEntity>().eq("code", s));
            if (ObjectUtils.isEmpty(empByCode)){
//                 empByCode = jobDaoMssql.findEmpByCode(s);
                Long professionJoblevelId = empByCode.getProfessionJoblevelId();
                Long managementJoblevelId = empByCode.getManagementJoblevelId();
                if (managementJoblevelId!=null){
                    empByCode.setJobLevelType(2);
                    empByCode.setJobLevelId(managementJoblevelId);
                }else {
                    empByCode.setJobLevelType(1);
                    empByCode.setJobLevelId(professionJoblevelId);
                }
            }

            empByCode.setCreateTime(new Date());
            empByCode.setUpdateTime(new Date());

            empByCode.setSocialTrainee("0");
            empByCode.setProbationday(3);
            Date hiredate = empByCode.getHiredate();
            Date date = DateUtils.addDateMonths(hiredate, 3);
            Date date1 = DateUtils.addDateDays(date, -1);
            empByCode.setRegularDay(date1);
            empByCode.setEmployeestatus("2");
            empByCode.setIsReinstate(0);
            empByCode.setStatus(3);
            empByCode.setIsHireDone(1);
            empByCode.setIsEntryStatus(1);

            empByCode.setIsSendContract(2);
            empByCode.setIsOffer(1);
//
            empByCode.setIsRegular(0);
            empByCode.setRegularIsDone(0);



            try {
                employeeInfoDao.updateById(empByCode);
            } catch (Exception e) {
                e.printStackTrace();
            }


//            EmployeeInfoEntity employeeInfoEntity = employeeInfoDao.selectOne(new QueryWrapper<EmployeeInfoEntity>().eq("code", s));





//            employeeInfoDao.updateById(employeeInfoEntity);
            i++;
        }
        System.out.println(i);



        return R.ok(i);

    }

    @Autowired
    private PromotionDao promotionDao;
    @Autowired
    private RegularBpmDao regularBpmDao;

    /**
     * 管理晋级转正导入
     * @return
     */
    @GetMapping("/test4")
    public R test4() {
//        File file = new File("/Users/lishenhong/Desktop/manager.txt");
//        BufferedReader reader = null;
//        String tempString = null;
//        int line =1;
////
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("ZT011687");





//        try {
//
//            reader = new BufferedReader(new FileReader(file));
//            while ((tempString = reader.readLine()) != null) {
//
//                arrayList.add(tempString);
//                line ++ ;
//            }
//            reader.close();
//        } catch (Exception e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//
//        }finally{
//            if(reader != null){
//                try {
//                    reader.close();
//                } catch (IOException e) {
//                    // TODO Auto-generated catch block
//                    e.printStackTrace();
//                }
//            }
//        }
        System.out.println(arrayList.size());
        int i=0;
        for (String s : arrayList) {
            EmployeeInfoEntity empByCode = employeeInfoDao.selectOne(new QueryWrapper<EmployeeInfoEntity>().eq("code", s));
//

//            PromotionEntity promotionEntity = new PromotionEntity();
//            promotionEntity.setOid(empByCode.getOid());
//            promotionEntity.setCode(empByCode.getCode());
//            promotionEntity.setBeforeOrgId(empByCode.getOrgId());
//            promotionEntity.setBeforeUnitId(empByCode.getUnitId());
//            promotionEntity.setBeforeJobLevelId(empByCode.getJobLevelId());
//            promotionEntity.setBeforeJobId(empByCode.getJobId());
//            promotionEntity.setPromotionKind(0);
//            promotionEntity.setIsDistribute(0);
//            promotionEntity.setIsRemind(1);
//            promotionEntity.setIsSelf(1);
//            promotionEntity.setStatus(3);
//            promotionEntity.setCreateTime(new Date());
//            promotionDao.insert(promotionEntity);

            PromotionEntity promotionEntity = promotionDao.selectOne(new QueryWrapper<PromotionEntity>().eq("code", s));
//            promotionEntity.setPromotionType(2);
//            promotionEntity.setName(empByCode.getName());
//           promotionEntity.setExpeditionDays(3);
//            Date endExpeditionDate = promotionEntity.getEndExpeditionDate();
//            promotionEntity.setPromotionDate(endExpeditionDate);
//            Long beforeOrgId = promotionEntity.getBeforeOrgId();
//            promotionEntity.setAfterOrgId(beforeOrgId);
//
//            Long beforeUnitId = promotionEntity.getBeforeUnitId();
//            promotionEntity.setAfterUnitId(beforeUnitId);
//
//            Long beforeJobId = promotionEntity.getBeforeJobId();
//            promotionEntity.setAfterJobId(beforeJobId);
//
//
//            promotionDao.updateById(promotionEntity);

            RegularBpmEntity regularBpmEntity = new RegularBpmEntity();
            regularBpmEntity.setOid(promotionEntity.getOid());
            regularBpmEntity.setRelationId(promotionEntity.getPromotionId());
            regularBpmEntity.setCode(promotionEntity.getCode());
            regularBpmEntity.setCreateTime(new Date());
            regularBpmEntity.setUseraccount(empByCode.getUseraccount());
            regularBpmEntity.setName(promotionEntity.getName());
            regularBpmEntity.setOrgId(promotionEntity.getAfterOrgId());
            regularBpmEntity.setUnitId(promotionEntity.getAfterUnitId());
            regularBpmEntity.setJobId(promotionEntity.getAfterJobId());
            regularBpmEntity.setHiredate(empByCode.getHiredate());
            regularBpmEntity.setRegularDay(promotionEntity.getEndExpeditionDate());
            regularBpmEntity.setRegularType(2);
            regularBpmEntity.setJobLevelType(2);
            regularBpmEntity.setJobLevelId(promotionEntity.getAfterJobLevelId());
            regularBpmEntity.setProbationday(3);
            regularBpmEntity.setBeforeOrgId(promotionEntity.getBeforeOrgId());
            regularBpmEntity.setBeforeUnitId(promotionEntity.getBeforeUnitId());
            regularBpmEntity.setBeforeJobLevelId(promotionEntity.getBeforeJobLevelId());
            regularBpmEntity.setBeforeJobId(promotionEntity.getBeforeJobId());
            regularBpmEntity.setApplyTime(promotionEntity.getBeginExpeditionDate());
            regularBpmEntity.setIsRegular(0);
            regularBpmDao.insert(regularBpmEntity);





            if (!ObjectUtils.isEmpty(promotionEntity)){
                i++;
            }

        }
        System.out.println(i);



        return R.ok(i);

    }


//    @GetMapping("/test5")
    public R test5() {
        File file = new File("/Users/lishenhong/Desktop/usercode.txt");
        BufferedReader reader = null;
        String tempString = null;
        int line =1;
//
        ArrayList<String> arrayList1 = new ArrayList<>();


        try {

            reader = new BufferedReader(new FileReader(file));
            while ((tempString = reader.readLine()) != null) {

                arrayList1.add(tempString);
                line ++ ;
            }
            reader.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }finally{
            if(reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        System.out.println(arrayList1.size());
        int i=0;
        ArrayList<Long> jobLevelId = new ArrayList<>();
        for (String s : arrayList1) {
            Long aLong = jobController.jobLevel.get(s);

            jobLevelId.add(aLong);


        }




        File file1 = new File("/Users/lishenhong/Desktop/manager.txt");
        BufferedReader reader1 = null;
        String tempString1 = null;
        int line1 =1;
//
        ArrayList<String> codeList = new ArrayList<>();


        try {

            reader1 = new BufferedReader(new FileReader(file1));
            while ((tempString1 = reader1.readLine()) != null) {

                codeList.add(tempString1);
                line1 ++ ;
            }
            reader1.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }finally{
            if(reader1 != null){
                try {
                    reader1.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }


        for (int i1 = 0; i1 < codeList.size(); i1++) {

            String s = codeList.get(i1);
            PromotionEntity promotionEntity = promotionDao.selectOne(new QueryWrapper<PromotionEntity>().eq("code", s));
            Long aLong = jobLevelId.get(i1);
            System.out.println(aLong);
            promotionEntity.setAfterJobLevelId(aLong);
            promotionDao.updateById(promotionEntity);
        }





        return R.ok(i);

    }


//    @Autowired
//    RedisIdWorker redisIdWorker;
//    @GetMapping("/test11")
//    public R idTest( ){
//        String contract=null;
//        for (int i = 0; i < 300; i++) {
//            contract = redisIdWorker.getStringId("contract");
//        }
//
//        return R.ok(contract);
//    }








    public static void main(String[] args) throws Exception {

        System.out.println("Select * from tb_employee_info where is_delete = 0 " +
                "and (is_regular = 0 or is_regular = 2) " +
                "and employeestatus = 2 " +
                "and regular_is_done = 0 " +
                "and is_entry_status = 1 " +
                "and is_regular_remind = 0 " +
                "and TIMESTAMPDIFF(DAY,regular_day,#{time}) <=20");

        String s = AESUtil.aesEncrypt("123456");


    }



}
